package com.ksxy.afingerprint.utils

import android.annotation.TargetApi
import android.os.Build
import android.security.keystore.KeyProperties
import android.util.Base64
import java.security.Key
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec

/**
 *  author : chenyinying
 *  e-mail : me@korion.cn
 *  time   : 2018/07/07
 *  desc   :
 *  version: 1.0
 */
object CryptUtils {

    var iv: ByteArray? = null
    @TargetApi(Build.VERSION_CODES.M)
    fun getEncryptCipherUseKey(key: Key): Cipher{
        val cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES +
                "/"+KeyProperties.BLOCK_MODE_CBC +
                "/"+KeyProperties.ENCRYPTION_PADDING_PKCS7)
        //TODO: KeyPermanentlyInvalidatedException: Key permanently invalidated
        cipher.init(Cipher.ENCRYPT_MODE, key)
        iv = cipher.iv
        return cipher
    }

    @TargetApi(Build.VERSION_CODES.M)
    fun getDecryptCipherUseKey(key: Key): Cipher{
        val cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES +
                "/"+KeyProperties.BLOCK_MODE_CBC +
                "/"+KeyProperties.ENCRYPTION_PADDING_PKCS7)
        cipher.init(Cipher.DECRYPT_MODE, key, IvParameterSpec(iv))
        return cipher
    }

    fun encrypt2Base64Str(cipher: Cipher, raw: String): String{
        return Base64.encodeToString(cipher.doFinal(raw.toByteArray(Charsets.UTF_8)), Base64.NO_WRAP)
    }

    fun decryptFormBase64Str(cipher: Cipher, base64str: String): String{
        val bytes = Base64.decode(base64str, Base64.NO_WRAP)
        val rawBytes = cipher.doFinal(bytes)
        return String(rawBytes, Charsets.UTF_8)
    }
}